package com.woorigil.social.parser.wemakeprice;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONObject;
import org.jsoup.Jsoup;

import com.woorigil.social.HttpUtils;
import com.woorigil.social.domain.ProviderCode;

public class ShoppingSiteParser {
	String baseUrl = "http://www.wemakeprice.com/main/get_deal_more/${}?_=1374058303003&curr_deal_cnt=0&r_cnt=5000";
	
	static Map<Integer, List<String>> shoppingUrls = new HashMap<Integer, List<String>>() {{
		put(2, Arrays.asList("100100", "100200"));
		put(3, Arrays.asList("100300"));
		put(4, Arrays.asList("100500"));
		put(5, Arrays.asList("100600"));
		put(6, Arrays.asList("100400"));
		put(7, Arrays.asList("101000"));
		put(8, Arrays.asList("100100"));
		put(9, Arrays.asList("100700", "101100"));
		put(10, Arrays.asList("100800"));
		put(11, Arrays.asList("100900"));
		put(12, Arrays.asList("101200"));
	}};	

	private WemakeExtraDeal extractDealInfo(org.jsoup.nodes.Element element, int categoryId, org.jsoup.select.Elements td1s) {
		String metaId = element.attr("deal_id");
		String imageUrl = element.select(".box_thumb img").attr("original");
//		System.out.println("SHOPPING : " + ProviderCode.WM + " : " + metaId + " : " + imageUrl + " : " + categoryId);
		return new WemakeExtraDeal(ProviderCode.WM, metaId, imageUrl, categoryId);
	}
	
	public Map<String, WemakeExtraDeal> parse() {
		Map<String, WemakeExtraDeal> extraDeals = new HashMap<String, WemakeExtraDeal>();
		for (Entry<Integer, List<String>> entry : shoppingUrls.entrySet()) {
			for (String each : entry.getValue()) {
				try {
					String data = HttpUtils.execute(baseUrl.replace("${}", each));
					String html = new JSONObject(data).getString("html");
					org.jsoup.nodes.Document doc = Jsoup.parse(html);
					org.jsoup.select.Elements td1s = doc.select("li");
					
					for (org.jsoup.nodes.Element element : td1s) {
						WemakeExtraDeal extraDeal = extractDealInfo(element, entry.getKey(), td1s);
						extraDeals.put(extraDeal.getMetaId(), extraDeal);
					}
				} catch (Exception e) {
				}
			}
		}
		return extraDeals;
	}
}
